package org.jeecg.modules.xl.product.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.lang.StringUtils;
import org.jeecg.modules.xl.product.entity.XlProductInfo;
import org.jeecg.modules.xl.product.entity.XlProductPics;
import org.jeecg.modules.xl.product.service.IXlProductCustomerPriceService;
import org.jeecg.modules.xl.product.service.IXlProductInfoService;
import org.jeecg.modules.xl.product.service.IXlProductPicsService;
import org.jeecg.modules.xl.product.vo.XlProductInfoPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.query.QueryRuleEnum;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;


 /**
 * @Description: xl_product_info
 * @Author: jeecg-boot
 * @Date:   2024-10-18
 * @Version: V1.0
 */
@Api(tags="xl_product_info")
@RestController
@RequestMapping("/org/jeecg/modules/xl/xlProductInfo")
@Slf4j
public class XlProductInfoController {
	@Autowired
	private IXlProductInfoService xlProductInfoService;
	@Autowired
	private IXlProductPicsService xlProductPicsService;

	@Autowired
	private IXlProductCustomerPriceService xlProductCustomerPriceService;
	 @Value("${pichost}")
	 private String baseUrl;
	/**
	 * 分页列表查询
	 *
	 * @param xlProductInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "xl_product_info-分页列表查询")
	@ApiOperation(value="xl_product_info-分页列表查询", notes="xl_product_info-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<XlProductInfo>> queryPageList(XlProductInfo xlProductInfo,
													  @RequestParam(name="noIds", required=false) String noIds,
													  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
													  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
													  HttpServletRequest req) {
        // 自定义查询规则
        Map<String, QueryRuleEnum> customeRuleMap = new HashMap<>();
        // 自定义多选的查询规则为：LIKE_WITH_OR
        customeRuleMap.put("status", QueryRuleEnum.LIKE_WITH_OR);
        QueryWrapper<XlProductInfo> queryWrapper = QueryGenerator.initQueryWrapper(xlProductInfo, req.getParameterMap(),customeRuleMap);


        //过滤id集合，这段代码只用于创建订单时，商品选择
		if (StringUtils.isNotBlank(noIds)){
			queryWrapper.notIn("id", noIds.split(","));
			queryWrapper.notIn("upc_code", noIds.split(","));
		}
		queryWrapper.eq("type",xlProductInfo.getType());//不存在的数据库字段，需要手动设
		Page<XlProductInfo> page = new Page<XlProductInfo>(pageNo, pageSize);
		IPage<XlProductInfo> pageList = xlProductCustomerPriceService.queryListByPage(page,queryWrapper);// xlProductInfoService.page(page, queryWrapper);
		//String baseUrl = "http://47.93.163.105:8058/jeecg-boot/sys/common/static/";
		List<XlProductInfo> newRecordsList = new ArrayList<>();
		for(XlProductInfo xlProductInfoTemp : pageList.getRecords()){
			if(ObjectUtil.isNotEmpty(xlProductInfoTemp.getMainPic())) {
				xlProductInfoTemp.setMainPic(baseUrl + xlProductInfoTemp.getMainPic());
			}else{
				xlProductInfoTemp.setMainPic(baseUrl+ "/temp/nophoto.png");
			}
			newRecordsList.add(xlProductInfoTemp);
		}
		pageList.setRecords(newRecordsList);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param xlProductInfoPage
	 * @return
	 */
	@AutoLog(value = "xl_product_info-添加")
	@ApiOperation(value="xl_product_info-添加", notes="xl_product_info-添加")
    @RequiresPermissions("org.jeecg.modules.xl:xl_product_info:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody XlProductInfoPage xlProductInfoPage) {
		XlProductInfo xlProductInfo = new XlProductInfo();
		BeanUtils.copyProperties(xlProductInfoPage, xlProductInfo);
		xlProductInfoService.saveMain(xlProductInfo, xlProductInfoPage.getXlProductPicsList());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param xlProductInfoPage
	 * @return
	 */

	@ApiOperation(value="xl_product_info-编辑", notes="xl_product_info-编辑")
    @RequiresPermissions("org.jeecg.modules.xl:xl_product_info:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody XlProductInfoPage xlProductInfoPage) {
		XlProductInfo xlProductInfo = new XlProductInfo();
		BeanUtils.copyProperties(xlProductInfoPage, xlProductInfo);
		XlProductInfo xlProductInfoEntity = xlProductInfoService.getById(xlProductInfo.getId());
		if(xlProductInfoEntity==null) {
			return Result.error("未找到对应数据");
		}
		//String baseUrl = "http://47.93.163.105:8058/jeecg-boot/sys/common/static/";
		String tempMailPic = xlProductInfo.getMainPic();
		if(StrUtil.containsAny(tempMailPic,baseUrl)){
			String result = StrUtil.replace(tempMailPic, baseUrl, "");
			xlProductInfo.setMainPic(result);
		}
		xlProductInfoService.updateMain(xlProductInfo, xlProductInfoPage.getXlProductPicsList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "xl_product_info-通过id删除")
	@ApiOperation(value="xl_product_info-通过id删除", notes="xl_product_info-通过id删除")
    @RequiresPermissions("org.jeecg.modules.xl:xl_product_info:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		xlProductInfoService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "xl_product_info-批量删除")
	@ApiOperation(value="xl_product_info-批量删除", notes="xl_product_info-批量删除")
    @RequiresPermissions("org.jeecg.modules.xl:xl_product_info:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.xlProductInfoService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "xl_product_info-通过id查询")
	@ApiOperation(value="xl_product_info-通过id查询", notes="xl_product_info-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<XlProductInfo> queryById(@RequestParam(name="id",required=true) String id) {
		XlProductInfo xlProductInfo = xlProductInfoService.getById(id);
		if(xlProductInfo==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(xlProductInfo);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "产品图片通过主表ID查询")
	@ApiOperation(value="产品图片主表ID查询", notes="产品图片-通主表ID查询")
	@GetMapping(value = "/queryXlProductPicsByMainId")
	public Result<List<XlProductPics>> queryXlProductPicsListByMainId(@RequestParam(name="id",required=true) String id) {
		List<XlProductPics> xlProductPicsList = xlProductPicsService.selectByMainId(id);
		return Result.OK(xlProductPicsList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param xlProductInfo
    */
    @RequiresPermissions("org.jeecg.modules.xl:xl_product_info:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, XlProductInfo xlProductInfo) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<XlProductInfo> queryWrapper = QueryGenerator.initQueryWrapper(xlProductInfo, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
         List<String> selectionList = Arrays.asList(selections.split(","));
         queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<XlProductInfo> xlProductInfoList = xlProductInfoService.list(queryWrapper);

      // Step.3 组装pageList
      List<XlProductInfoPage> pageList = new ArrayList<XlProductInfoPage>();
      for (XlProductInfo main : xlProductInfoList) {
          XlProductInfoPage vo = new XlProductInfoPage();
          BeanUtils.copyProperties(main, vo);
          List<XlProductPics> xlProductPicsList = xlProductPicsService.selectByMainId(main.getId());
          vo.setXlProductPicsList(xlProductPicsList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "xl_product_info列表");
      mv.addObject(NormalExcelConstants.CLASS, XlProductInfoPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("xl_product_info数据", "导出人:"+sysUser.getRealname(), "xl_product_info"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("org.jeecg.modules.xl:xl_product_info:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
		  params.setSheetNum(1);	//只导入一个sheet数据
		  params.setStartSheetIndex(0);	//从第一个sheet开始导入
          params.setNeedSave(false);
          try {
              List<XlProductInfoPage> list = ExcelImportUtil.importExcel(file.getInputStream(), XlProductInfoPage.class, params);
			  //根据商品名称进行分组
			  Map<String, List<XlProductInfoPage>> groupedByName = list.stream()
					  .collect(Collectors.groupingBy(XlProductInfoPage::getProductName));

			  // 输出分组结果
			  for (Map.Entry<String, List<XlProductInfoPage>> entry : groupedByName.entrySet()) {
				  XlProductInfo po = new XlProductInfo();

				  List<XlProductInfoPage> xlProductInfoPages = entry.getValue();//这是每一个分组list，相当于一个订单
				  BeanUtils.copyProperties(xlProductInfoPages.get(0), po);//因为主表是重复了，所以第一行作为主表信息

				  //遍历xlProductInfoPages，取每一个picslist的明细数据，构建picslist
				  List<XlProductPics> xlProductPicsList = new ArrayList<>();
//				  for (int i  =0;i<xlProductInfoPages.size();i++){
//					  XlProductPics tmp = new XlProductPics();
//					  List<XlProductPics> xlProductPicsListTemp = xlProductInfoPages.get(i).getXlProductPicsList();
//					  if (ObjectUtil.isNotEmpty(xlProductPicsListTemp)){
//						  BeanUtils.copyProperties(xlProductPicsListTemp.get(0),tmp);
//						  xlProductPicsList.add(tmp);
//					  }
//
//				  }

				  xlProductInfoService.saveMain(po, xlProductPicsList);
			  }
//              for (XlProductInfoPage page : list) {
//                  XlProductInfo po = new XlProductInfo();
//                  BeanUtils.copyProperties(page, po);
//                  xlProductInfoService.saveMain(po, page.getXlProductPicsList());
//              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

}
